Macromedia Flex Article

Learning Flex Basics (Part 2): Creating a Simple Calculator with Macromedia Flex


Table of Contents

  1. Introduction
  2. Building the Calculator
  3. Create the Application Object
  4. Add a Panel for the Calculator
  5. Add the Calculator Display
  6. Add a Grid to Lay Out the Buttons
  7. Add the Calculator Buttons
  8. Create the CalculatorController Class
  9. Add Properties to the Controller Class
  10. Add Controller Methods
  11. Instantiate the CalculatorController Class
  12. Complete Code Listing for calculator.mxml
  13. Complete Code Listing for CalculatorController.as
  14. Where to Go From Here

Create the CalculatorController Class

Create an ActionScript class that will be a controller for the calculator. Because the application is simple, you will include the data model in the controller rather than create it separately.

Creating a class in ActionScript is simple and is similar to the way you create one in other object-oriented languages. The basic syntax is:

class ClassName
{
	[properties and methods]
}

Save classes as .as files; the file name must be the same as the class name.

Although the compiler will generate an empty constructor if the class definition does not contain one, it is good practice to include a constructor, even if it does nothing. Constructor methods in ActionScript may not take parameters or return any values, and constructor overloading is not supported. Constructors, like other methods, are created using the function keyword:

[public|private] function ClassName(){}

Methods (and properties) are public by default, meaning that they can be accessed from outside the class. It's good practice to always make them public or private explicitly as a reminder to make them private if they don't need to be public.

  1. Open a new empty file and save it as CalculatorController.as in the same directory as your calculator.mxml file.
  2. Add a class definition for the CalculatorController class:

    class CalculatorController
    {}
    
  3. Add an empty constructor function inside the class block:

    public function CalculatorController(){}